package com.cmcc.volte.xdr;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.cmcc.pcap.voltePcapParse.PcapParser;

import com.cmcc.sdtp.util.SdtpPropertiesUtil;

import com.cmcc.volte.www.signal.UtilAction;
import com.cmcc.volte.xdr.SigXDR.SigXDR;
import com.cmcc.volte.xdr.XDRUtil.SequenceUtil;
import com.cmcc.volte.xdr.XDRUtil.XDRUtil;
import com.cmcc.volte.xdr.sequence.Arrow;
import com.cmcc.volte.xdr.sequence.ComparatorArrow;
import com.cmcc.volte.xdr.util.JSONUtils;
import com.cmcc.volte.xdr.util.StyleConversionUtils;
import com.cmcc.xdr.entity.ComposedEntity;

/**
 * @comment xdr数据反查方法
 * @author B
 * @date 2015-9-21
 * @version 1.0
 */
public class UtilService {

	private static DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	private static Logger logger = LogManager.getLogger(UtilService.class);

	/**
	 * @Comments 反查，记录查询功能中的反查原始信令入口
	 * @param interFace
	 * @param xdrId
	 * @param startTime 注：该值单位要求是秒，XDR的ProcedureStartTime的单位是毫秒
	 * @Vsersion: 1.0
	 */
	public static String getSequenceStr2(int interFace, String xdrId, long startTime,String defaultName,String directory) {
//		HashMap<String, Object> map = getSequence2Map(interFace,xdrId,startTime,defaultName);
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			
//			List<Arrow> arrowList = null;
//			List<String> nodeList = new ArrayList<String>();
//			Map<String, String> mapping = new HashMap<String, String>();
//			SigXDR sigXDR = getXdr.getSigXDR(interFace, xdrId, startTime,defaultName);
//			arrowList = XDRUtil.xdrArrow(sigXDR);
//			ComparatorArrow comparator = new ComparatorArrow();
//			Collections.sort(arrowList, comparator);
//			int index = 1;
//			for (Arrow arrow : arrowList) {
			List<Arrow> arrowList = null;
			List<String> nodeList = new ArrayList<String>();
			Map<String, String> mapping = new LinkedHashMap<String, String>();
			SigXDR sigXDR = GetXdr.getSigXDR(interFace, xdrId, startTime,defaultName);
			arrowList = XDRUtil.xdrArrow(sigXDR);
			ComparatorArrow comparator = new ComparatorArrow();
			Collections.sort(arrowList, comparator);
			int index = 1;
			Double firstTime = 0d;//第一次的值（这个需要和后面的值进行相减）
			DecimalFormat decf = new DecimalFormat("0.000");
			for (Arrow arrow : arrowList) {
				String dtns = java.lang.Math.abs(arrow.getDateTime_ns())+"";
				if(dtns.length() != 9){
					String qianbuwei = ""; //如果纳秒长度不够9位则前补0
					for (int i = 0; i < 9-dtns.length(); i++) {
						qianbuwei = qianbuwei+"0";
					}
					dtns = qianbuwei + dtns;
				}
				String jianTime = "";//和第一次相减过后的值
				String time = arrow.getDateTime_s() + dtns.substring(0, 3);
				Date date=new Date(Long.parseLong(time));
				String timeStr = df.format(date);//最后的时间带毫秒的
				if(index == 1){
					firstTime = Double.parseDouble(time) / 1000;
					jianTime = "0";
				}else{
					Double xiayige = Double.parseDouble(time) / 1000;
//					System.out.println(time+"--"+xiayige+"==="+firstTime);
					jianTime = decf.format((xiayige - firstTime));
				}
				
				String remark = index + "." + arrow.getRemark()+"@|"+timeStr+"@|"+jianTime+"s";

//				String remark = index + "." + arrow.getRemark();
//				String remark = index + "." + arrow.getRemark()+"@|2016-09-27 15:30:25."+index+"@|0."+index;
				remark = remark.replaceAll("\r\n", "");
				arrow.setRemark(remark);
				//对只有哦数字的remark加消息类型
				if(SequenceUtil.remarkUtil(arrow)!=null){
					arrow.setRemark(SequenceUtil.remarkUtil(arrow));
				} 
	//			arrow.setRemark(index + "." + arrow.getRemark());
				mapping.put(arrow.getRemark(), arrow.getComment());
				if (!nodeList.contains(arrow.getSrcNode())) {
					nodeList.add(arrow.getSrcNode());
				}
				if (!nodeList.contains(arrow.getDestNode())) {
					nodeList.add(arrow.getDestNode());
				}
				index++;
			}
			PcapParser parser = new PcapParser();
			Map<String,Map<String,String>> headerMap = parser.getHeaderMap(xdrId,defaultName,directory);
			map.put("sequence", SequenceUtil.pcap2svg(nodeList, arrowList));
			map.put("mapping", StyleConversionUtils.styleConversion(mapping));
			map.put("headerMap", headerMap);
			map.put("statusType", sigXDR.getStatusType());

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("信令解析出错，查找默认的信令",e);

			List<Arrow> arrowList = null;
			List<String> nodeList = new ArrayList<String>();
			Map<String, String> mapping = new LinkedHashMap<String, String>();
			SigXDR sigXDR = GetXdr.getSigXDR(interFace, defaultName, startTime,defaultName);
			arrowList = XDRUtil.xdrArrow(sigXDR);
			ComparatorArrow comparator = new ComparatorArrow();
			Collections.sort(arrowList, comparator);
			int index = 1;
			for (Arrow arrow : arrowList) {
				String remark = index + "." + arrow.getRemark();
				remark = remark.replaceAll("\r\n", "");
				arrow.setRemark(remark);
	//			arrow.setRemark(index + "." + arrow.getRemark());
				mapping.put(arrow.getRemark(), arrow.getComment());
				if (!nodeList.contains(arrow.getSrcNode())) {
					nodeList.add(arrow.getSrcNode());
				}
				if (!nodeList.contains(arrow.getDestNode())) {
					nodeList.add(arrow.getDestNode());
				}
				index++;
			}
			PcapParser parser = new PcapParser();
			Map<String,Map<String,String>> headerMap = parser.getHeaderMap(xdrId,defaultName,directory);
			map.put("sequence", SequenceUtil.pcap2svg(nodeList, arrowList));
			map.put("mapping", StyleConversionUtils.styleConversion(mapping));
			map.put("headerMap", headerMap);
			map.put("statusType", 102);
		}
		return JSONUtils.mapToJSON(map);
	}
	
	/**
	  * 记录评估调用的反查入口
	 * @param interFace
	 * @param xdrId
	 * @param startTime 注：该值单位要求是秒，XDR的ProcedureStartTime的单位是毫秒
	 * @param defaultName
	 * @return
	 */
	public synchronized static HashMap<String, Object> getSequence2Map(int interFace, String xdrId, long procedureStartTime,String defaultName) {
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeString = format.format(procedureStartTime);
        Long startTime = UtilAction.caculateStartTime(timeString);
	    HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			
//			List<Arrow> arrowList = null;
//			List<String> nodeList = new ArrayList<String>();
//			Map<String, String> mapping = new HashMap<String, String>();
//			SigXDR sigXDR = getXdr.getSigXDR(interFace, xdrId, startTime,defaultName);
//			arrowList = XDRUtil.xdrArrow(sigXDR);
//			ComparatorArrow comparator = new ComparatorArrow();
//			Collections.sort(arrowList, comparator);
//			int index = 1;
//			for (Arrow arrow : arrowList) {
			List<Arrow> arrowList = null;
			List<String> nodeList = new ArrayList<String>();
			Map<String, String> mapping = new LinkedHashMap<String, String>();
			Map<Integer, String> portMap = new HashMap<Integer, String>();
			SigXDR sigXDR = GetXdr.getSigXDR(interFace, xdrId, startTime,defaultName);
			arrowList = XDRUtil.xdrArrow(sigXDR);
			ComparatorArrow comparator = new ComparatorArrow();
			Collections.sort(arrowList, comparator);
			int index = 1;
			Double firstTime = 0d;//第一次的值（这个需要和后面的值进行相减）
			DecimalFormat decf = new DecimalFormat("0.000");
			for (Arrow arrow : arrowList) {
				String dtns = java.lang.Math.abs(arrow.getDateTime_ns())+"";
				if(dtns.length() != 9){
					String qianbuwei = ""; //如果纳秒长度不够9位则前补0
					for (int i = 0; i < 9-dtns.length(); i++) {
						qianbuwei = qianbuwei+"0";
					}
					dtns = qianbuwei + dtns;
				}
				String jianTime = "";//和第一次相减过后的值
				String time = arrow.getDateTime_s() + dtns.substring(0, 3);
				Date date=new Date(Long.parseLong(time));
				String timeStr = df.format(date);//最后的时间带毫秒的
				if(index == 1){
					firstTime = Double.parseDouble(time) / 1000;
					jianTime = "0";
				}else{
					Double xiayige = Double.parseDouble(time) / 1000;
//					System.out.println(time+"--"+xiayige+"==="+firstTime);
					jianTime = decf.format((xiayige - firstTime));
				}
				
				String remark = index + "." + arrow.getRemark()+"@|"+timeStr+"@|"+jianTime+"s";

//				String remark = index + "." + arrow.getRemark();
//				String remark = index + "." + arrow.getRemark()+"@|2016-09-27 15:30:25."+index+"@|0."+index;
				remark = remark.replaceAll("\r\n", "");
				arrow.setRemark(remark);
				//对只有哦数字的remark加消息类型
				if(SequenceUtil.remarkUtil(arrow)!=null){
					arrow.setRemark(SequenceUtil.remarkUtil(arrow));
				} 
	//			arrow.setRemark(index + "." + arrow.getRemark());
				mapping.put(arrow.getRemark(), arrow.getComment());
				if (!nodeList.contains(arrow.getSrcNode())) {
					nodeList.add(arrow.getSrcNode());
				}
				if (!nodeList.contains(arrow.getDestNode())) {
					nodeList.add(arrow.getDestNode());
				}
				portMap.put(index, arrow.getSrcNePort()+"@|"+arrow.getDestNePort());
				index++;
			}
			map.put("sequence", SequenceUtil.pcap2svg(nodeList, arrowList));
			map.put("mapping", mapping);
			map.put("statusType", sigXDR.getStatusType());
			map.put("portMap",portMap);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("信令解析出错，查找默认的信令",e);

			List<Arrow> arrowList = null;
			List<String> nodeList = new ArrayList<String>();
			Map<String, String> mapping = new LinkedHashMap<String, String>();
			Map<Integer, String> portMap = new HashMap<Integer, String>();
			SigXDR sigXDR = GetXdr.getSigXDR(interFace, defaultName, startTime,defaultName);
			arrowList = XDRUtil.xdrArrow(sigXDR);
			ComparatorArrow comparator = new ComparatorArrow();
			Collections.sort(arrowList, comparator);
			int index = 1;
			for (Arrow arrow : arrowList) {
				String remark = index + "." + arrow.getRemark();
				remark = remark.replaceAll("\r\n", "");
				arrow.setRemark(remark);
	//			arrow.setRemark(index + "." + arrow.getRemark());
				mapping.put(arrow.getRemark(), arrow.getComment());
				if (!nodeList.contains(arrow.getSrcNode())) {
					nodeList.add(arrow.getSrcNode());
				}
				if (!nodeList.contains(arrow.getDestNode())) {
					nodeList.add(arrow.getDestNode());
				}
				portMap.put(index, arrow.getSrcNePort()+"@|"+arrow.getDestNePort());
				index++;
			}
			map.put("sequence", SequenceUtil.pcap2svg(nodeList, arrowList));
			map.put("mapping", mapping);
			map.put("statusType", 102);
			map.put("portMap",portMap);
		}
		return map;
	}
	
	/**
	 * @Comments 合成xdr信令图
	 * @param interFace
	 * @param xdrId
	 * @param startTime
	 * @Vsersion: 1.0
	 */
	public static String getComposedStr(List<ComposedEntity> listComposed) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<String> nodeList = new ArrayList<String>();
		Map<String, String> mapping = new HashMap<String, String>();
		List<Arrow> arrowList = new ArrayList<Arrow>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		String sequenceStr = "";
		int status = 0;
		try {
			for (ComposedEntity composedEntity : listComposed) {
				try {
					Long startTime = 0l;
					if(composedEntity.getProcedureStartTime() != null){
						String timeString = format.format(composedEntity.getProcedureStartTime());
						startTime = UtilAction.caculateStartTime(timeString);
					}
					SigXDR sigXDR = GetXdr.getSigXDR(composedEntity.getInterface(), composedEntity.getSingleXdrId(), startTime, "");
					if(sigXDR.getStatusType() == 101){
						continue;
					}
					List<Arrow> arrowListSon = XDRUtil.xdrArrow(sigXDR);
					for (Arrow arrow : arrowListSon) {
						arrowList.add(arrow);//先合起来，然后统一进行处理
					}
					status ++;
				} catch (Exception e) {
					logger.info("合成xdr:"+composedEntity.getXdrId()+",子xdr:"+composedEntity.getSingleXdrId()+"信令单个解析错误！！",e);
//					System.out.println("合成xdr:"+composedEntity.getXdrId()+",子xdr:"+composedEntity.getSingleXdrId()+"信令单个解析错误！！"+e);
					continue;
				}
			}
			if(status > 0 && listComposed.size() > 0){//如果解析正确，则进行一下，否则查询默认
				ComparatorArrow comparator = new ComparatorArrow();
				Collections.sort(arrowList, comparator);
				int index = 1;
				Double firstTime = 0d;//第一次的值（这个需要和后面的值进行相减）
				DecimalFormat decf = new DecimalFormat("0.000");
				for (Arrow arrow : arrowList) {
					String dtns = java.lang.Math.abs(arrow.getDateTime_ns())+"";
					if(dtns.length() != 9){
						String qianbuwei = ""; //如果纳秒长度不够9位则前补0
						for (int i = 0; i < 9-dtns.length(); i++) {
							qianbuwei = qianbuwei+"0";
						}
						dtns = qianbuwei + dtns;
					}
					String jianTime = "";//和第一次相减过后的值
					String time = arrow.getDateTime_s() + dtns.substring(0, 3);
					Date date=new Date(Long.parseLong(time));
					String timeStr = df.format(date);//最后的时间带毫秒的
					if(index == 1){
						firstTime = Double.parseDouble(time) / 1000;
						jianTime = "0";
					}else{
						Double xiayige = Double.parseDouble(time) / 1000;
						jianTime = decf.format((xiayige - firstTime));
					}
					
					String remark = index + "." + arrow.getRemark()+"@|"+timeStr+"@|"+jianTime+"s";
					remark = remark.replaceAll("\r\n", "");
					
//					String remark = index + "." + arrow.getRemark();
//					remark = remark.replaceAll("\r\n", "");
					arrow.setRemark(remark);
					//对只有哦数字的remark加消息类型
					if(SequenceUtil.remarkUtil(arrow)!=null){
						arrow.setRemark(SequenceUtil.remarkUtil(arrow));
					} 
					mapping.put(arrow.getRemark(), arrow.getComment());
					if (!nodeList.contains(arrow.getSrcNode())) {
						nodeList.add(arrow.getSrcNode());
					}
					if (!nodeList.contains(arrow.getDestNode())) {
						nodeList.add(arrow.getDestNode());
					}
					index++;
				}
				map.put("sequence", SequenceUtil.pcap2svg(nodeList, arrowList));
				map.put("mapping", mapping);
				map.put("statusType", 100);
			}else{
				sequenceStr = SdtpPropertiesUtil.getProperty("DEFAULT_SIPCALL_COMPOSED");
				return sequenceStr;
			}
			
		} catch (Exception e) {
			sequenceStr = SdtpPropertiesUtil.getProperty("DEFAULT_SIPCALL_COMPOSED");
			return sequenceStr;
		}
		return JSONUtils.mapToJSON(map);
		
	}

}